package sc.analysis.rsi;


import java.io.IOException;

import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import sc.writable.IntermediateData;
import sc.writable.IntermediateData.Type;


/**
 * Reducer of the Relative Strength Indicator.
 * 
 * TODO advanced RSI (RSI med/long term trend) see http://stockcharts.com/
 * school/doku.php?id=chart_school:technical_indicators:relative_strength_in
 *
 * @author Quentin Rossé
 *
 */
public class RsiReducer extends Reducer<Text, FloatWritable, 
                                        Text, IntermediateData> {
	
	private static final String ANALYSIS_NAME = "RSI";
	
	/**
	 * Number of days for the analysis
	 */
	private static final int PERIOD = 14;
	
	/**
	 * data written for the next phase
	 */
	private static IntermediateData imd = new IntermediateData();
	
	@Override
	public void reduce(Text key, Iterable<FloatWritable> values, Context context) throws IOException, InterruptedException {
		float rsi;
		for(FloatWritable fw : values){
			rsi = fw.get();
			imd.setType(PERIOD);
			imd.setScore(score(rsi));
			imd.setDetails("RSI value : " + rsi);
			context.write(key, imd);
			
			if(rsi > 70f){
				imd.setScore(1);
				imd.setType(Type.ALERT_BEAR);
				imd.setDetails("Overbougt");
				context.write(key, imd);
			}
			else if (rsi < 30f){
				imd.setScore(1);
				imd.setType(Type.ALERT_BULL);
				imd.setDetails("Oversold");
				context.write(key, imd);
			}
		}
	}
	
	@Override
	public void setup(Context context){
		imd.setAnalysisName(ANALYSIS_NAME);
	}
	
	@Override
	public void cleanup(Context context){}
	
	/**
	 * Return the score from the RSI value
	 * 
	 * @param rsi RSI value
	 * @return
	 */
	private int score(double rsi){
		return 10 - (int)(rsi/10f);
	}
}